package com.briup.gsauestore.service.impl;

import com.briup.gsauestore.bean.Shop;
import com.briup.gsauestore.bean.ShopCar;
import com.briup.gsauestore.bean.User;
import com.briup.gsauestore.dao.IShopCarDao;
import com.briup.gsauestore.service.IShopCarService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @author adam
 * @date 2022/1/12
 */
@Service
public class ShopCarServiceImpl implements IShopCarService {
    @Autowired
    private IShopCarDao shopCarDao;
    @Override
    public List<ShopCar> findUserAllShopCar(Long userId) {
        List<ShopCar> list = shopCarDao.findByUserId(userId);
        return list;
    }

    @Override
    public void saveShopCar(Long userId,Long shopId) {
        ShopCar shopCar = shopCarDao.findByUserIdAndShopId(userId, shopId);
//        判断当前用户是否对当前商品进行过加购行为
        if(Objects.isNull(shopCar)){
            shopCar=new ShopCar();
            shopCar.setNum(1);
            Shop shop = new Shop();
            shop.setId(shopId);
            User user = new User();
            user.setId(userId);
            shopCar.setShop(shop);
            shopCar.setUser(user);
        }else {
            shopCar.setNum(shopCar.getNum()+1);
        }
        shopCarDao.save(shopCar);

    }

    @Override
    public void deleteShopCar(Long id) {
        shopCarDao.deleteById(id);
    }

    @Override
    public void updateShopCar(Long id, int num) {
shopCarDao.updateNumById(num,id);
    }

    @Override
    public List<ShopCar> findShopCars(Long[] ids) {
        ArrayList<ShopCar> list = new ArrayList<>();
        for (Long id : ids) {
            Optional<ShopCar> optional = shopCarDao.findById(id);
            ShopCar car = optional.get();
            list.add(car);
        }
        return  list;
    }
}
